package cn.iocoder.yudao.framework.base.common.mysql.sequence;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

/**
 * DROP TABLE IF EXISTS `system_seq`;
 * CREATE TABLE `system_seq` (
 *   `seq_name` varchar(50) NOT NULL,
 *   `current_val` int(11) NOT NULL,
 *   `increment_val` int(11) NOT NULL DEFAULT '1',
 *   PRIMARY KEY (`seq_name`)
 * ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
 *
 * DELIMITER $$
 * DROP FUNCTION IF EXISTS  curr_val $$
 * CREATE  FUNCTION `curr_val`(v_seq_name VARCHAR(50)) RETURNS int(11)
 * begin
 *  declare value integer;
 *  set value = 0;
 *  select current_val into value  from system_seq where seq_name = v_seq_name;
 *    return value;
 * end $$
 *
 * DROP FUNCTION IF EXISTS  next_val $$
 * CREATE  FUNCTION `next_val`(v_seq_name VARCHAR(50)) RETURNS int(11)
 * begin
 *     update system_seq set current_val = current_val + increment_val  where seq_name = v_seq_name;
 *     return curr_val(v_seq_name);
 * end $$
 * DELIMITER ;
 */
@Repository
public interface SeqMapper {

    @Select("select curr_val(#{seq_name})" )
    Long currVal(@Param("seq_name" ) String seq_name);

    @Select("select next_val(#{seq_name})" )
    Long nextVal(@Param("seq_name" ) String seq_name);


    @Select("select count(*) as count  from system_seq where seq_name =#{seq_name}" )
    int countSeq(@Param("seq_name" ) String seq_name);

    @Insert("INSERT INTO `system_seq` (`seq_name`, `current_val`, `increment_val`) VALUES (#{seq_name}, '0', '1')" )
    int insert(@Param("seq_name" ) String seq_name);


}
